package org.jeecg.modules.api.withdraw.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ijpay.core.kit.IpKit;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.app.WechatUtil;
import org.jeecg.config.vo.WxPayVo;
import org.jeecg.modules.api.member.mapper.MemberMapper;
import org.jeecg.modules.api.member.service.IMemberService;
import org.jeecg.modules.api.withdraw.entity.WithdrawRecord;
import org.jeecg.modules.api.withdraw.service.IWithdrawRecordService;

import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 提现记录
 * @Author: jeecg-boot
 * @Date: 2024-10-21
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "提现记录")
@RestController
@RequestMapping("/withdraw/withdrawRecord")
public class WithdrawRecordController extends JeecgController<WithdrawRecord, IWithdrawRecordService> {
    @Autowired
    private IWithdrawRecordService withdrawRecordService;
    @Autowired
    private MemberMapper memberMapper;
    @Value("${sys.online}")
    private Boolean online;

    /**
     * 分页列表查询
     *
     * @param withdrawRecord
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "提现记录-分页列表查询")
    @ApiOperation(value = "提现记录-分页列表查询", notes = "提现记录-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(WithdrawRecord withdrawRecord,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<WithdrawRecord> queryWrapper = QueryGenerator.initQueryWrapper(withdrawRecord, req.getParameterMap());
        Page<WithdrawRecord> page = new Page<WithdrawRecord>(pageNo, pageSize);
        IPage<WithdrawRecord> pageList = withdrawRecordService.page(page, queryWrapper);
        return Result.OK(pageList);
    }
//
//	/**
//	 * 添加
//	 *
//	 * @param withdrawRecord
//	 * @return
//	 */
//	@AutoLog(value = "提现记录-添加")
//	@ApiOperation(value="提现记录-添加", notes="提现记录-添加")
//	@PostMapping(value = "/add")
//	public Result<?> add(@RequestBody WithdrawRecord withdrawRecord) {
//		withdrawRecordService.save(withdrawRecord);
//		return Result.OK("添加成功！");
//	}

    /**
     * 审核
     *
     * @param withdrawRecord
     * @return
     */
    @AutoLog(value = "提现记录-审核")
    @ApiOperation(value = "提现记录-审核", notes = "提现记录-审核")
    @PostMapping(value = "/audit")
    public Result<?> audit(@RequestBody WithdrawRecord withdrawRecord, HttpServletRequest request) {
        WithdrawRecord entity = withdrawRecordService.getById(withdrawRecord.getId());
        int res = withdrawRecordService.updatState(entity.getId(), 0, withdrawRecord.getState());
        if (res == 0) {
            return Result.error("操作失败！状态已经变更，请刷新页面");
        }
        if (withdrawRecord.getState() == 1) {//审核通过
            String ip = IpKit.getRealIp(request);
            if (StringUtils.isBlank(ip)) {
                ip = "127.0.0.1";
            }
            if(!online){
                entity.setMoney(BigDecimal.valueOf(0.01));//测试1分钱
            }
            WxPayVo wxPay = new WxPayVo();
            wxPay.setTrade_no(entity.getId());
            wxPay.setMoney(entity.getMoney());
            wxPay.setOpenid(entity.getOpenid());
            wxPay.setDesc("用户提现");
            wxPay.setIp(ip);
            boolean result = WechatUtil.wxPay(wxPay);
            if (result) {
                withdrawRecordService.updatState(entity.getId(), 1, 2);
            } else {
                withdrawRecordService.updatState(entity.getId(), 1, 0);
            }
            return result ? Result.OK("操作成功") : Result.error("操作失败");
        } else if (withdrawRecord.getState() == 3) { //取消
          int ress =  memberMapper.addWithdrawMoney(entity.getMemberId(),entity.getMoney());
            log.info("审核不通过：addWithdrawMoney {}",ress);
            return Result.OK("操作成功！");
        }
        return Result.error("审核状态错误！");
    }

//	/**
//	 * 编辑
//	 *
//	 * @param withdrawRecord
//	 * @return
//	 */
//	@AutoLog(value = "提现记录-编辑")
//	@ApiOperation(value="提现记录-编辑", notes="提现记录-编辑")
//	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
//	public Result<?> edit(@RequestBody WithdrawRecord withdrawRecord) {
//		withdrawRecordService.updateById(withdrawRecord);
//		return Result.OK("编辑成功!");
//	}

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "提现记录-通过id删除")
    @ApiOperation(value = "提现记录-通过id删除", notes = "提现记录-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        withdrawRecordService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "提现记录-批量删除")
    @ApiOperation(value = "提现记录-批量删除", notes = "提现记录-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.withdrawRecordService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "提现记录-通过id查询")
    @ApiOperation(value = "提现记录-通过id查询", notes = "提现记录-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        WithdrawRecord withdrawRecord = withdrawRecordService.getById(id);
        return Result.OK(withdrawRecord);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param withdrawRecord
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WithdrawRecord withdrawRecord) {
        return super.exportXls(request, withdrawRecord, WithdrawRecord.class, "提现记录");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, WithdrawRecord.class);
    }

}
